<template>
  <div class="dialog__container">
    <el-dialog
      v-model="dialogVisible"
      title="新增角色组"
      draggable
      width="650px"
      :before-close="beforeClose"
    >
      <div class="dialog__body__container">
        <el-form
          ref="ruleFormRef"
          style="max-width: 600px"
          :model="ruleForm"
          :rules="rules"
          label-width="auto"
          class="demo-ruleForm"
          status-icon
        >
          <el-form-item label="角色组名" prop="name">
            <el-input
              v-model="ruleForm.name"
              placeholder="请输入权限名称"
              clearable
            />
          </el-form-item>
          <el-form-item label="父级角色组" prop="pid">
            <el-tree-select
              v-model="ruleForm.pid"
              :data="roleList"
              check-strictly
              node-key="id"
              :render-after-expand="false"
              :props="{
                label: 'name',
              }"
            >
            </el-tree-select>
          </el-form-item>
          <el-form-item label="权限" prop="rules">
            <el-tree-select
              v-model="ruleForm.rules"
              :data="permissionList"
              :render-after-expand="false"
              :props="{
                label: 'name',
              }"
              node-key="id"
              show-checkbox
              multiple
            />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm(ruleFormRef)">
            确定
          </el-button>
          <el-button @click="resetForm(ruleFormRef)">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup name="AddRoleDialog">
defineOptions({
  name: "AddRoleDialog",
  inheritAttrs: false,
});
import { getPermissionList } from "@/api/permission/index";
import { addAdminGroup, editAdminGroup } from "@/api/role/index";
import { type RoleForm } from "@/api/role/types";
import type { FormInstance, FormRules } from "element-plus";
const emit = defineEmits("success");

const dialogVisible = ref<boolean>(false);
const permissionList = ref<any[]>([]); // 权限列表
const roleList = ref<any[]>([]); // 角色组列表
const isEdit = ref<boolean>(false);
const handleOpen = (
  data: { isEdit: boolean; row: any | null },
  adminGroupList: any[]
) => {
  roleList.value = [
    { label: "无", name: "无", id: 0 },
    ...JSON.parse(JSON.stringify(adminGroupList)),
  ];
  isEdit.value = data.isEdit;
  if (isEdit.value) {
    ruleForm.name = data.row.name;
    ruleForm.pid = data.row.pid;
    ruleForm.id = data.row.id;
    ruleForm.rules =
      data.row.rules?.split(",")?.map((elm: any) => Number(elm)) || [];
  }
  console.log("打开弹窗后的 form  ", ruleForm);
  console.log("打开弹窗后的 isEdit  ", isEdit.value);
  dialogVisible.value = true;
};
defineExpose({
  handleOpen,
});

// 关闭函数
const beforeClose = (done: any) => {
  ruleForm.name = "";
  ruleForm.pid = "";
  ruleForm.route = "";
  isEdit.value = false;
  if (typeof done === "function") {
    done();
  } else {
    dialogVisible.value = false;
  }
};

// 获取权限列表
const getPermissionListService = async () => {
  let params = {
    // page: 1,
    // limit: 0,
  };
  let res = await getPermissionList(params);
  if (res) {
    console.log("权限列表返回结果 ", res);
    permissionList.value = [...res.data.list];
  }
};
getPermissionListService();

// 新增权限
const addOrEditAdminGroupService = async () => {
  let data: RoleForm = {
    ...ruleForm,
  };
  console.log("提交data  ", data);
  if (Number(data.pid) === 0) {
    data.pid = "";
  }
  if (!isEdit.value) {
    delete data.id;
  }
  if (data.rules && Array.isArray(data.rules)) {
    data.rules = data.rules.join(",");
  }
  let res = !isEdit.value
    ? await addAdminGroup(data)
    : await editAdminGroup(data.id ? data.id : "", data);
  if (res) {
    console.log("新增成功  ", res);
    ElMessage({
      type: "success",
      message: !isEdit.value ? "新增成功" : "修改成功",
    });
    emit("success");
    dialogVisible.value = false;
    resetForm(ruleFormRef.value);
  }
};


const ruleFormRef = ref<FormInstance>();
const ruleForm = reactive<RoleForm>({
  name: "",
  id: "",
  rules: "",
});

const rules = reactive<FormRules<RoleForm>>({
  name: [{ required: true, message: "请输入角色组名称", trigger: "blur" }],
  pid: [{ required: true, message: "请选择父级角色组", trigger: "blur" }],
});

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log("submit!");
      addOrEditAdminGroupService();
    } else {
      console.log("error submit!", fields);
    }
  });
};

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
  beforeClose(null);
  dialogVisible.value = false;
};
</script>

<style lang="scss" scoped>
.dialog__container {
  .dialog__body__container {
    box-sizing: border-box;
    padding-right: 15px;
    max-height: 70vh;
    overflow-y: auto;
  }
}
</style>
